/*
 * Copyright 2013 Alibaba.com All right reserved. This software is the
 * confidential and proprietary information of Alibaba.com ("Confidential
 * Information"). You shall not disclose such Confidential Information and shall
 * use it only in accordance with the terms of the license agreement you entered
 * into with Alibaba.com.
 */
package com.madding.shared.encrypt.cert.gen;

import java.math.BigInteger;
import java.security.InvalidKeyException;
import java.security.KeyPair;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.SignatureException;
import java.security.cert.CertificateEncodingException;
import java.security.cert.X509Certificate;

import org.bouncycastle.x509.X509V1CertificateGenerator;

import com.madding.shared.encrypt.cert.bc.model.CertModel;
import com.madding.shared.encrypt.cert.constants.CertConstants;
import com.madding.shared.encrypt.cert.exception.TDCertException;

/**
 * 类SingleX509V1Creator.java的实现描述：TODO 类实现描述
 * 
 * @author madding.lip Dec 5, 2013 9:34:02 AM
 */
public class SingleX509V1Creator implements CertConstants {

    public static X509Certificate generateV1Certificate(CertModel certModel, KeyPair pair) throws TDCertException {

        try {
            X509V1CertificateGenerator certGen = new X509V1CertificateGenerator();
            certGen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis()));
            certGen.setIssuerDN(certModel.getIssueName());
            certGen.setNotBefore(certModel.getNotBefore());
            certGen.setNotAfter(certModel.getNotAfter());
            certGen.setSubjectDN(certModel.getSubjectName());
            certGen.setPublicKey(pair.getPublic());
            certGen.setSignatureAlgorithm(SHA256_RSA);
            return certGen.generate(pair.getPrivate(), BC_JCE);
        } catch (CertificateEncodingException e) {
            throw new TDCertException(e);
        } catch (InvalidKeyException e) {
            throw new TDCertException(e);
        } catch (IllegalStateException e) {
            throw new TDCertException(e);
        } catch (NoSuchProviderException e) {
            throw new TDCertException(e);
        } catch (NoSuchAlgorithmException e) {
            throw new TDCertException(e);
        } catch (SignatureException e) {
            throw new TDCertException(e);
        }
    }
}
